#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@version: 0.1
@author: 张宇洁
@contact: a_ff1984@163.com
@site: https://gitee.com/InsignificantDust
@software: PyCharm
@file: tools.py.py
@time: 2021/7/2 11:12
"""

import logging
from logging.handlers import RotatingFileHandler
from logging import StreamHandler
import sys
import pymysql
from pymysql.cursors import DictCursor


class Logger:

    def __call__(self, project_name, log_file, maxBytes, backupCount, fmt, level):
        self.project = project_name
        self.log = log_file
        self.logger = logging.getLogger(self.project)
        fileHandler = RotatingFileHandler(self.log, "a", maxBytes, backupCount, encoding='utf-8')
        fmt = logging.Formatter(fmt)
        fileHandler.setFormatter(fmt)
        fileHandler.setLevel(level)
        consoleHandler = StreamHandler(sys.stdout)
        consoleHandler.setFormatter(fmt)
        consoleHandler.setLevel(level)
        self.logger.addHandler(fileHandler)
        self.logger.addHandler(consoleHandler)
        self.logger.setLevel(level)
        return self.logger


class DB(object):
    """
    自用数据库工具：
    example:
    with Db(host="host", user="user", password="password", port="port", db="database") as db:
        db.exceute(sql, *args)
        results = db.fetchall()
    """
    def __init__(self, host=None, user=None, password=None, port=3306, db=None):
        self._host = host
        self._user = user
        self._password = password
        self._port = port
        self._db = db

    @property
    def db(self):
        return self._db

    @db.setter
    def db(self, name):
        self._db = name

    def connect(self):
        self.connections = pymysql.Connect(host=self._host,
                                           user=self._user,
                                           password=self._password,
                                           port=self._port,
                                           db=self.db,
                                           cursorclass=DictCursor)
        self.connections.connect()
        self.cursor = self.connections.cursor()
        return self

    def close(self):
        self.cursor.close()
        self.connections.close()

    def __enter__(self):
        self.connect()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


def parse_string(paramstr, encoding="utf8"):
    """
    将存储的十六进制内容转换为字符串
    :param paramstr: 十六进制内容
    :param encoding: 字符编码
    :return: str
    """
    return bytes.fromhex(paramstr).decode(encoding)


def convert_string(paramstr, encoding='utf8'):
    """
    将字符串转换为十六进制内容
    :param paramstr: 源字符串
    :param encoding: 字符编码
    :return: str
    """
    return bytes(paramstr, encoding).hex()
